package com.base.lib.ui;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.base.lib.R;
import com.base.lib.mvp.present.BasePresenter;
import com.base.lib.mvp.view.IBaseView;
import com.base.lib.ui.dialog.LoadingDialog;
import com.base.lib.util.EventBusUtil;
import com.base.lib.util.InputMethodUtils;
import com.base.lib.util.StringUtils;
import com.base.lib.util.ToastUtil;

/**
 * @author neo.duan
 * @date 2019/09/09
 * @desc BaseAppActivity
 */
public abstract class BaseAppActivity<P extends BasePresenter> extends AppCompatActivity implements IBaseView {

    public Context mContext;
    protected P mPresenter;
    public Toolbar mToolBar;
    TextView mTvLeft;
    TextView mTvRight;
    TextView mTvTitle;
    public ViewGroup mContainer;
    LoadingDialog mLoadingDialog;

    int mMenuResId;

    private View.OnClickListener mNavLeftClickListener;
    private View.OnClickListener mNavRightClickListener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mContext = this;

        super.setContentView(R.layout.activity_base);

        initBaseView();

        setContentView(getLayoutResId());
        /***初始化intent****/
        if (getIntent() != null) {
            initIntent(getIntent());
        }
        /***初始化标题栏****/
        initTop();
        /***初始化内容view****/
        initView(savedInstanceState);
        /***初始化事件监听****/
        initListeners();
        /***初始化present****/
        mPresenter = (P) initPresenter();
        initData();
    }

    private void initBaseView() {
        mToolBar = findViewById(R.id.base_toolBar);
        mTvLeft = findViewById(R.id.tv_left_text);
        mTvTitle = findViewById(R.id.tv_base_title);
        mTvRight = findViewById(R.id.tv_right_text);
        mContainer = findViewById(R.id.fl_content_container);

        if (useEventBus()) {
            EventBusUtil.register(this);
        }

        supportActionBar(mToolBar);
    }


    public boolean useEventBus() {
        return false;
    }

    protected void supportActionBar(Toolbar toolbar) {
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setTitle("");
            mToolBar.setNavigationIcon(R.drawable.ic_arrow_back);
        }
        toolbar.setNavigationOnClickListener(
                (v) -> onBackPressed()
        );
    }

    @Override
    public void setContentView(int layoutResID) {
        if (layoutResID != 0) {
            setContentView(View.inflate(this, layoutResID, null));
        }
    }

    @Override
    public void setContentView(View contentView) {
        mContainer.removeAllViews();
        mContainer.addView(contentView);
    }

    public void initIntent(Intent intent) {

    }

    protected void enableTop(boolean enable) {
        mToolBar.setVisibility(enable ? View.VISIBLE : View.GONE);
    }

    protected void enableBack(boolean enable) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(enable);
        }
    }

    protected void enableBack(boolean enable, View.OnClickListener listener) {
        enableBack(enable);
        this.mNavLeftClickListener = listener;
    }

    protected void enableBack(int iconResId, View.OnClickListener listener) {
        mToolBar.setNavigationIcon(iconResId);
        this.mNavLeftClickListener = listener;
    }

    protected void enableBack(String text, View.OnClickListener listener) {
        if (!TextUtils.isEmpty(text)) {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(false);
            }
            mTvLeft.setVisibility(View.VISIBLE);
            mTvLeft.setText(text);
            mTvLeft.setOnClickListener(listener);
        } else {
            mTvLeft.setVisibility(View.GONE);
        }
    }

    protected void setTitle(String title) {
        mTvTitle.setText(StringUtils.nullStrToEmpty(title));
    }

    protected void enableRight(boolean enable) {
        if (!enable) {
            mMenuResId = 0;
        }
        invalidateOptionsMenu();
    }

    protected void enableRight(String text, View.OnClickListener listener) {
        if (!TextUtils.isEmpty(text)) {
            mTvRight.setVisibility(View.VISIBLE);
            mTvRight.setText(text);
            mTvRight.setOnClickListener(listener);
        } else {
            mTvRight.setVisibility(View.GONE);
        }
    }

    protected void enableRight(int menuResId, View.OnClickListener listener) {
        this.mMenuResId = menuResId;
        this.mNavRightClickListener = listener;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mMenuResId != 0) {
            getMenuInflater().inflate(R.menu.menu_activity_base_top_bar, menu);
        }
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (mMenuResId != 0) {
            menu.findItem(R.id.menu_1).setIcon(mMenuResId);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (mNavLeftClickListener != null) {
                mNavLeftClickListener.onClick(item.getActionView());
            }
        } else if (item.getItemId() == R.id.menu_1) {
            if (mNavRightClickListener != null) {
                mNavRightClickListener.onClick(item.getActionView());
            }
        }

        return true;
    }

    @Override
    public Context getContext() {
        return mContext;
    }

    @Override
    public void showLoading() {
        showLoading("正在加载");
    }

    @Override
    public void showLoading(String message) {
        if (this.isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            synchronized (LoadingDialog.class) {
                if (mLoadingDialog == null) {
                    mLoadingDialog = new LoadingDialog(mContext);
                }
            }
        }
        mLoadingDialog.setMessage(message);
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (null != mLoadingDialog) {
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
        }
    }

    /**
     * 点击空白位置 隐藏软键盘
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodUtils.hideInputMethod(this);
        return super.onTouchEvent(event);
    }

    @Override
    public void showNetError() {

    }

    @Override
    public void showEmptyView() {

    }

    @Override
    public void showMessage(String msg) {
        if (isFinishing() || TextUtils.isEmpty(msg)) {
            return;
        }
        ToastUtil.show(getApplicationContext(), msg);
    }

    protected void addFragment(Fragment fragment, int viewGroupId) {
        doFragmentOperation(0, fragment, viewGroupId, false);
    }

    protected void removeFragment(Fragment fragment) {
        doFragmentOperation(1, fragment, 0, false);
    }

    protected void replaceFragment(Fragment fragment, int viewGroupId, boolean addToBackStack) {
        doFragmentOperation(2, fragment, viewGroupId, addToBackStack);
    }

    private void doFragmentOperation(int fragmentOperation, Fragment fragment, int viewGroupId, boolean addToBackStack) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        switch (fragmentOperation) {
            case 0:
                fragmentTransaction.add(viewGroupId, fragment);
                break;
            case 1:
                fragmentTransaction.remove(fragment);
                break;
            case 2:
                fragmentTransaction.replace(viewGroupId, fragment);
                break;
            default:
                break;
        }

        if (addToBackStack) {
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }

    @Override
    protected void onDestroy() {
        if (useEventBus()) {
            EventBusUtil.unregister(this);
        }
        super.onDestroy();
    }

    protected abstract void initTop();

    protected abstract int getLayoutResId();

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void initListeners();

    protected abstract BasePresenter initPresenter();

    protected abstract void initData();


}
